package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDto;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import sun.awt.image.GifImageDecoder;

import javax.annotation.Resource;

import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FEED_EMAIL_KEY;
import static com.hmdp.utils.RedisConstants.LIKE_BLOG_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    /**
     * 查询博客
     *
     * @param id 博客id
     * @return 结果
     */
    @Override
    public Result queryBlogById(Long id) {
        // 查询Blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("博客不存在");
        }
        // 查询Blog用户信息
        User user = userService.getById(blog.getUserId());
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        // 判断用户是否点赞
        Double isMember = stringRedisTemplate.opsForZSet()
                .score(LIKE_BLOG_KEY + id, String.valueOf(user.getId()));
        if (isMember != null) {
            blog.setIsLike(true);
        }
        return Result.ok(blog);
    }

    /**
     * 博客点赞
     *
     * @param id 博客id
     * @return 结果
     */
    @Override
    public Result likeBlog(Long id) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 判断用户是否点赞
        Double isMember = stringRedisTemplate.opsForZSet()
                .score(LIKE_BLOG_KEY + id, String.valueOf(userId));
        if (isMember == null) {
            // 保存用户ID到Redis，并加入时间戳作为score
            stringRedisTemplate.opsForZSet().add(LIKE_BLOG_KEY + id, String.valueOf(userId), System.currentTimeMillis());
            // 数据库点赞+1
            update().setSql("liked = liked + 1").eq("id", id).update();
            return Result.ok("点赞成功");
        }
        return Result.fail("您已经点过赞了");
    }

    /**
     * 查询博客点赞列表
     *
     * @param id 博客id
     * @return 结果
     */
    @Override
    public Result queryBlogLikes(Long id) {
        // 查询top5的点赞用户
        Set<String> range = stringRedisTemplate.opsForZSet()
                .range(LIKE_BLOG_KEY + id, 0, 4);
        if (range == null || range.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> top5 = range.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
        // 查询用户
        List<UserDto> collect = userService.listByIds(top5).stream()
                .map(user -> BeanUtil.copyProperties(user, UserDto.class))
                .collect(Collectors.toList());
        return Result.ok(collect);
    }

    /**
     * 保存博客
     *
     * @param blog 博客
     * @return 结果
     */
    @Override
    public Result saveBlog(Blog blog) {
        /* 保存探店笔记 */
        // 获取登录用户
        UserDto user = UserHolder.getUser();
        // 保存探店博文
        blog.setUserId(user.getId());
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("保存失败");
        }

        /* Feed流推送粉丝-推模式 */
        // 查询自己所有粉丝
        List<Follow> follows = followService.list(Wrappers.<Follow>lambdaQuery()
                .eq(Follow::getFollowUserId, user.getId()));
        // 推送最新BlogId + 时间戳
        for (Follow follow : follows) {
            // 获取粉丝ID
            Long fansId = follow.getUserId();
            // 推送粉丝ZSet
            String key = FEED_EMAIL_KEY + fansId;
            stringRedisTemplate.opsForZSet().add(key, String.valueOf(blog.getId()), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    /**
     * 查询关注的人的博客推送信息
     *
     * @param max    当前查询最大时间戳
     * @param offset 偏移量
     * @return 结果
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        // 滚动查询收件箱
        String key = FEED_EMAIL_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 解析收件箱blogId、minTime、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0L;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if (time == minTime) {
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        // 封装Blog返回
        List<Blog> blogs = listByIds(ids);
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }
}
